/**
     * WebSocket客户端工具，提供非Hook环境下的WebSocket功能
     */

    // WebSocket服务器URL配置
    const WS_URL = process.env.NODE_ENV === 'production' 
      ? 'wss://api.example.com/ws' 
      : 'ws://localhost:3001/ws';

    class SocketClient {
      constructor(namespace = '') {
        this.namespace = namespace;
        this.socket = null;
        this.isConnected = false;
        this.messageHandlers = {};
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 3000;
        this.reconnectTimeout = null;
      }

      /**
       * 连接到WebSocket服务器
       * @returns {Promise<void>} 连接成功或失败的Promise
       */
      connect() {
        return new Promise((resolve, reject) => {
          // 清除之前的重连定时器
          if (this.reconnectTimeout) {
            clearTimeout(this.reconnectTimeout);
            this.reconnectTimeout = null;
          }

          // 如果已经连接，先关闭
          if (this.socket && (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING)) {
            this.socket.close();
          }

          try {
            // 构建WebSocket URL
            const url = this.namespace ? `${WS_URL}/${this.namespace}` : WS_URL;
            
            // 添加token（如果有）
            const token = localStorage.getItem('authToken');
            const wsUrl = token ? `${url}?token=${token}` : url;
            
            // 创建WebSocket连接
            this.socket = new WebSocket(wsUrl);
            
            // 设置事件处理器
            this.socket.onopen = () => {
              this.isConnected = true;
              this.reconnectAttempts = 0;
              console.log('WebSocket连接已建立');
              resolve();
            };
            
            this.socket.onclose = (event) => {
              this.isConnected = false;
              console.log('WebSocket连接已关闭', event);
              this._attemptReconnect();
            };
            
            this.socket.onerror = (event) => {
              console.error('WebSocket连接错误', event);
              reject(new Error('WebSocket连接错误'));
            };
            
            this.socket.onmessage = (event) => {
              try {
                const data = JSON.parse(event.data);
                
                // 调用对应事件类型的处理函数
                if (data.type && this.messageHandlers[data.type]) {
                  this.messageHandlers[data.type].forEach(handler => handler(data));
                }
                
                // 调用通用消息处理函数
                if (this.messageHandlers['*']) {
                  this.messageHandlers['*'].forEach(handler => handler(data));
                }
              } catch (err) {
                console.error('解析WebSocket消息时出错:', err);
              }
            };
          } catch (err) {
            console.error('WebSocket连接失败:', err);
            reject(err);
          }
        });
      }

      /**
       * 尝试重新连接
       * @private
       */
      _attemptReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          this.reconnectAttempts++;
          console.log(`尝试重新连接WebSocket (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
          
          this.reconnectTimeout = setTimeout(() => {
            this.connect().catch(() => {
              // 连接失败，继续尝试
              this._attemptReconnect();
            });
          }, this.reconnectInterval);
        } else {
          console.error('WebSocket重连失败，已达到最大尝试次数');
        }
      }

      /**
       * 发送消息到WebSocket服务器
       * @param {string} type - 消息类型
       * @param {Object} data - 消息数据
       * @returns {boolean} 是否发送成功
       */
      send(type, data = {}) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
          const message = JSON.stringify({
            type,
            ...data,
            timestamp: new Date().toISOString(),
          });
          
          this.socket.send(message);
          return true;
        } else {
          console.error('WebSocket未连接，无法发送消息');
          return false;
        }
      }

      /**
       * 添加消息处理函数
       * @param {string} type - 消息类型，使用'*'表示处理所有消息
       * @param {Function} handler - 处理函数
       * @returns {Function} 用于移除处理函数的函数
       */
      on(type, handler) {
        if (!this.messageHandlers[type]) {
          this.messageHandlers[type] = [];
        }
        
        this.messageHandlers[type].push(handler);
        
        // 返回一个函数，用于移除此处理函数
        return () => {
          this.off(type, handler);
        };
      }

      /**
       * 移除消息处理函数
       * @param {string} type - 消息类型
       * @param {Function} handler - 处理函数
       */
      off(type, handler) {
        if (this.messageHandlers[type]) {
          this.messageHandlers[type] = this.messageHandlers[type].filter(h => h !== handler);
          if (this.messageHandlers[type].length === 0) {
            delete this.messageHandlers[type];
          }
        }
      }

      /**
       * 断开WebSocket连接
       */
      disconnect() {
        if (this.socket) {
          this.socket.close();
          this.socket = null;
        }
        
        if (this.reconnectTimeout) {
          clearTimeout(this.reconnectTimeout);
          this.reconnectTimeout = null;
        }
        
        this.isConnected = false;
        console.log('WebSocket连接已断开');
      }
    }

    // 创建默认实例
    const socketClient = new SocketClient();

    export default socketClient;
    export { SocketClient };
